<!--
 * @Description:选择座位
 * @Author: Kerwin
 * @Date: 2025-04-27 17:30:11
 * @LastEditTime: 2025-05-30 12:01:39
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="seat-container">
    <!-- 展示选座提示信息 -->
    <van-notice-bar
      color="red"
      left-icon="volume-o"
      text="“重要提醒：由于系统特性，当前座位选择后不会临时锁定，若其他用户先完成支付，您选中的座位可能失效，请尽快完成选座哦～”"
    />
    <!-- 影院屏幕 -->
    <view class="screen-area">
      <!-- 倒计时 -->
      <view
        class="time-warning"
        v-if="showWarning && !isStopSell"
        style="
          color: red;
          font-size: 30rpx;
          font-weight: bold;
          display: flex;
          align-items: center;
          justify-content: center;
        "
      >
        距售票结束时间：<u-count-down
          :timestamp="remainTime * 1000"
          format="mm分ss秒"
        ></u-count-down>
      </view>
      <!-- 图例 -->
      <view class="legend">
        <view class="legend-item">
          <view class="legend-color available"></view>
          <view>可选</view>
        </view>
        <!-- <view class="legend-item">
          <view class="legend-color selected"></view>
          <view>已选</view>
        </view> -->
        <view class="legend-item">
          <view class="legend-color disabled"></view>
          <view>不可选</view>
        </view>
        <view class="legend-item">
          <view class="legend-color lover"> </view>
          <view>情侣座</view>
        </view>
        <!-- 重新加载图标 -->
        <u-icon
          name="reload"
          size="40"
          @click="getAllSeat(sessionInfo)"
          style="cursor: pointer; margin-left: 60rpx"
        ></u-icon>
      </view>
      <view class="screen-arch">
        <u-image src="../../static/gx.png" width="405rpx" height="21rpx">
        </u-image>
      </view>
      <view class="screen-label">{{ sessionInfo.hallName }}</view>
    </view>
    <!-- 座位区域 -->
    <view
      class="seating-area"
      :style="seatingAreaStyle"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >
      <view class="row-labels" :style="{ 'font-size': labelFontSize + 'rpx' }">
        <view
          v-for="(zw, index) in showSeatList"
          :key="'label-' + index"
          class="row-label"
          :style="{ height: seatSize + 'rpx' }"
        >
          {{ index + 1 }}
        </view>
      </view>
      <view class="seats-container">
        <view
          v-for="zw in showSeatList"
          :key="'row-' + zw.rowNo"
          class="seat-row"
          :style="{
            justifyContent: shouldCenterSeats ? 'center' : 'flex-start'
          }"
        >
          <view
            v-for="col in maxColumns"
            :key="col"
            :style="{
              width: seatSize + 'rpx',
              height: seatSize + 'rpx',
              'font-size': seatFontSize + 'rpx',
              ...getSeatStyle(zw.rowNo, col)
            }"
            :class="[
              'seatKuai',
              getSeatStatus(zw.rowNo, col),
              {
                selected: isSeatSelected(zw.rowNo, col),
                'couple-left': getSeat(zw.rowNo, col)?.loveStatus === 1,
                'couple-right': getSeat(zw.rowNo, col)?.loveStatus === 2
              }
            ]"
            @click="handleClickSeat(zw.rowNo, col)"
          >
            <!-- 添加勾选图标 -->
            <u-icon
              v-if="isSeatSelected(zw.rowNo, col)"
              name="checkmark"
              color="#fff"
              size="20"
              style="
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
              "
            ></u-icon>
          </view>
        </view>
      </view>
    </view>
    <view
      style="
        color: #007aff;
        font-size: 17rpx;
        text-align: center;
        padding-top: 10rpx;
      "
      >温馨提示:座位区域可上下滚动，可双指进行放大缩小操作</view
    >
    <!-- 价格图例 -->
    <view class="legend-container" v-if="hasAreaPricing">
      <view
        class="legend-item"
        v-for="area in getAllAreaPrices"
        :key="'price-legend-' + area.areaId"
      >
        <view class="legend-color" :style="{ borderColor: area.color }"></view>
        <view>￥{{ area.price }}</view>
      </view>
    </view>
    <view class="footer">
      <!--  电影信息和已选座位-->
      <view class="movie-area">
        <view class="bt">
          <view style="font-size: 32rpx; font-weight: bold">{{
            movieInfo.movieName
          }}</view>
          <view style="margin-left: 20rpx; flex: 1" class="overwz">{{
            cinemaName
          }}</view>
        </view>
        <view style="margin-bottom: 20rpx">
          <text style="color: #ff6c18">{{ showWeekName }} </text>
          <text style="margin: 0 5rpx">{{ movieDate }}</text>
          <text style="margin-right: 5rpx"> {{ movieTime }}</text>
          <text>
            {{ sessionInfo.showVersionType }}
          </text>
        </view>
        <!-- 展示已选座位 -->
        <view v-if="selectedSeatList.length > 0" class="yxzw">
          <view
            class="yxzw-item"
            v-for="(zw, index) in selectedSeatList"
            :key="zw.seatId"
          >
            <view class="yxzw-l">
              <view> {{ zw.seatNo.replace('列', '座') }}</view>
              <view class="jq">
                <view>￥{{ zw.zsjg }}</view>
              </view>
            </view>
            <view class="yxzw-r">
              <u-icon
                name="close"
                color="#999"
                size="28"
                @click="handleCancleSeat(index)"
              ></u-icon>
            </view>
          </view>
        </view>
        <!--总价和优惠  -->
        <view class="jgbox" v-if="selectedSeatList.length > 0">
          <view style="margin-bottom: 5rpx"
            >总价:<text class="redwz" style="font-weight: bold">
              ￥{{ calculatePrice.acturePayTotalPrice }}</text
            >
            <text class="hxwz">￥{{ calculatePrice.baseTotalPrice }}</text>
          </view>
          <view class="txbox">
            总抵扣:
            <view
              class="redwz"
              style="margin-left: 10rpx; height: 28rpx; line-height: 35rpx"
              >{{ calculatePrice.totalDiscount }}</view
            >
            <u-image
              width="32rpx"
              height="28rpx"
              src="../../static/yhq.png"
            ></u-image>
          </view>
        </view>
      </view>
      <!-- 选择座位按钮-->
      <view class="btn-area">
        <button
          v-if="!isStopSell"
          :disabled="selectedSeatList.length == 0"
          class="select-btn"
          :class="{
            'disabled-btn': selectedSeatList.length == 0
          }"
          @click="hanleClickSelectSeatBtn"
        >
          {{ showText }}
        </button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, useTransitionState, watch } from 'vue'
import { movieApi, moneyApi, enumAll } from '@/api'
import {
  onLoad,
  onShow,
  onUnload,
  onReachBottom,
  onHide
} from '@dcloudio/uni-app'
import {
  IMovieInfo,
  ICinemaInfo,
  ISession,
  ISeat,
  IAreaPrice,
  IGroupedSeats
} from '@/packageF/components/movieInterface'
const cinemaName = ref(uni.getStorageSync('xzCinemaName'))
// 添加缩放相关变量
const initialDistance = ref(0)
const currentScale = ref(1)
const isScaling = ref(false)
let reloadTimer: number | null = null
let isPageActive = false // 标记页面是否活跃
let currentPageRoute = '' // 记录当前页面路由
// 剩余时间（秒）
const remainTime = ref(0)
// 是否显示30分钟警告
const showWarning = ref(false)
// 是否已停止售卖
const isStopSell = ref(false)
let timer: number | null = null
// 显示的日期文字
const showWeekName = ref('')
// 是否放大或缩小
const isZoomed = ref(false)
const containerWidth = ref(750) // 调整为750rpx
// 进一步减小最小座位宽度
const minSeatSize = ref(3)
// 压缩状态下的座位间距
const seatSpacing = ref(5) // 减小到4rpx
// 已选择的座位
const selectedSeatList = ref<ISeat[]>([])
const sessionDate = ref<string[]>([])
const cinemaId = ref('')
const sessionId = ref('')
// 最多选择的座位数
const maxNum = ref(0)
const seatList = ref<ISeat[]>([])
// 用户拥有的总的复来券
const useTotalFulaiquan = ref(0)
// 用户拥有的总的花积分
const useTotalHuajifen = ref(0)
// 用户拥有的总的现金抵用券
const useToatlChanglaiQuan = ref(0)
//模式类型
const shopMode = ref(JSON.parse(uni.getStorageSync('hyType')).id)
const sessionInfo = ref<ISession>({
  showId: '',
  hallName: '',
  movieId: 0,
  duration: 0,
  showTime: '',
  stopShowTime: '',
  stopSellTime: '',
  showVersionType: '',
  showPrice: 0,
  userMoney: 0,
  userPrice: 0,
  userScoreMoney: 0,
  areaPrice: []
})
const movieInfo = ref<IMovieInfo>({
  movieName: '',
  grade: '',
  duration: '',
  movieType: '',
  posterUrl: '',
  publishDate: '',
  intro: '',
  cast: '',
  director: '',
  publishStatus: '',
  movieId: ''
})
interface IRow {
  rowNo: string
  seats: {
    [columnNo: string]: ISeat
  }
}

onLoad(async (option: any) => {
  console.log('选座shopMode', shopMode.value)
  currentPageRoute = getCurrentPages().pop()?.route || ''
  if (shopMode.value == 1) {
    await getMemberTotalHuajifen()
  } else if (shopMode.value == 4) {
    await getMemberTotalFulaiquan()
  } else if (shopMode.value == 6) {
    await getMemberTotalChangLaiQuan()
  }
})
onShow(() => {
  movieInfo.value = JSON.parse(uni.getStorageSync('movieData'))
  movieInfo.value.movieType = movieInfo.value.movieType.replaceAll('|', ',')
  sessionInfo.value = JSON.parse(uni.getStorageSync('sessionData'))
  cinemaId.value = JSON.parse(uni.getStorageSync('xzCinemaId'))
  showWeekName.value = uni.getStorageSync('xzWeekName')
  getAllSeat(sessionInfo.value)
  initCountdown() // 初始化倒计时
  isPageActive = true
  // 如果当前页面是选座页，才启动定时刷新
  // console.log('currentPageRoute', currentPageRoute)
  if (currentPageRoute === 'packageF/pages/selectSeat/index') {
    startSeatRefresh()
  }
})
//页面卸载时清除缓存，通过navigateTo跳转不会卸载页面
onUnload(() => {
  console.log('选座页面卸载')
  clearAllTimers()
  uni.removeStorageSync('xzCinemaId')
  isPageActive = false
  // console.log('isPageActive', isPageActive)
  // console.log(timer, 'timer')
  // console.log('reloadTimer', reloadTimer)
})
// 离开页面清除定时器
onHide(() => {
  console.log('选座页面离开')
  clearAllTimers()
  isPageActive = false
  // console.log('isPageActive', isPageActive)
  // console.log(timer, 'timer')
  // console.log('reloadTimer', reloadTimer)
})

// 计算属性
// 按钮显示文字
const showText = computed(() => {
  if (selectedSeatList.value.length > 0) {
    return '确认选座'
  } else {
    return '请选择座位'
  }
})
// 电影日期
const movieDate = computed(() => {
  const tempArr = sessionInfo.value.showTime.split(' ')[0].split('-')
  return `${tempArr[1]}月${tempArr[2]}日`
})
// 开场时间
const movieTime = computed(() => {
  return sessionInfo.value.showTime.split(' ')[1].slice(0, 5)
})
// 是否有分区定价
const hasAreaPricing = computed(() => {
  // 存在 areaPrice 且至少有一个区域的 area 值不为 null/undefined
  return sessionInfo.value.areaPrice?.some((area) => area.area != null) || false
})
// 计算最大列数
const maxColumns = computed(() => {
  return Math.max(...seatList.value.map((seat) => parseInt(seat.columnNo)))
})
// 展示的座位
const showSeatList = computed<IRow[]>(() => {
  const rowsMap: Record<string, IRow> = {}
  seatList.value.forEach((seat: ISeat) => {
    if (!rowsMap[seat.rowNo]) {
      rowsMap[seat.rowNo] = {
        rowNo: seat.rowNo,
        seats: {}
      }
    }
    rowsMap[seat.rowNo].seats[seat.columnNo] = seat
  })

  return Object.values(rowsMap).sort(
    (a, b) => parseInt(a.rowNo) - parseInt(b.rowNo)
  )
})
//座位区域是否需要居中
const shouldCenterSeats = computed(() => {
  // 仅在非放大状态且列数小于等于26时居中
  return !isZoomed.value && maxColumns.value <= 26
})

// 清除所有定时器
const clearAllTimers = () => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  if (reloadTimer) {
    clearTimeout(reloadTimer)
    reloadTimer = null
  }
}
// 计算两点间距离
const getDistance = (touches: TouchList) => {
  if (touches.length < 2) return 0
  const dx = touches[0].clientX - touches[1].clientX
  const dy = touches[0].clientY - touches[1].clientY
  return Math.sqrt(dx * dx + dy * dy)
}
// 触摸开始事件
const handleTouchStart = (e: TouchEvent) => {
  if (e.touches.length === 2) {
    initialDistance.value = getDistance(e.touches)
    isScaling.value = true
    e.preventDefault() // 阻止默认行为
  }
}
// 触摸移动事件
const handleTouchMove = (e: TouchEvent) => {
  if (e.touches.length === 2 && isScaling.value) {
    const currentDistance = getDistance(e.touches)
    if (initialDistance.value > 0) {
      const scale = currentDistance / initialDistance.value
      currentScale.value = Math.max(
        0.5,
        Math.min(scale * currentScale.value, 2)
      )
      e.preventDefault() // 阻止默认行为
    }
  }
}
// 触摸结束事件
const handleTouchEnd = () => {
  isScaling.value = false
  initialDistance.value = 0
  // 应用缩放状态（接近1时为正常，否则为放大）
  isZoomed.value = currentScale.value > 1.1
}
// 修改座位尺寸计算
const seatSize = computed(() => {
  const baseSize = isZoomed.value
    ? 30
    : Math.max(10, ((containerWidth.value - 40) / maxColumns.value) * 0.65)
  return baseSize * currentScale.value
})
// 修改seating-area的样式绑定
const seatingAreaStyle = computed(() => ({
  width: isZoomed.value ? 'auto' : `${containerWidth.value}rpx`,
  overflowX: isZoomed.value ? 'auto' : 'hidden',
  margin: '0 auto' // 居中显示;
}))
// 字体大小计算保持比例
const seatFontSize = computed(() => Math.max(10, seatSize.value * 0.5))
const labelFontSize = computed(() => seatSize.value * 0.35)
// 计算用户拥有的总的券
const userHasTotalTicket = computed(() => {
  switch (shopMode.value) {
    case 1:
      return useTotalHuajifen.value
    case 4:
      return useTotalFulaiquan.value
    case 6:
      return useToatlChanglaiQuan.value
    // 添加默认返回值
    default:
      return 0
    // // 如果确定 shopMode 只会是 1、4、6，可以断言不会走到这里
    // default:
    //   throw new Error('未处理的 shopMode 值')
  }
})
// 计算价格
const calculatePrice = computed(() => {
  // 1. 计算最低支付金额总和（保留两位小数），不能用userMinMoney，因为是优惠券足够的情况下计算的值，并且是不会随着优惠券的变化而变化
  const totalMinMoney = parseFloat(
    selectedSeatList.value
      .reduce((sum, seat) => sum + seat.userMoney, 0)
      .toFixed(2)
  )
  // 2. 计算座位抵扣金额总和（保留两位小数）
  const totalSeatScoreMoney = parseFloat(
    selectedSeatList.value
      .reduce((sum, seat) => sum + seat.userScoreMoney, 0)
      .toFixed(2)
  )
  // 3. 计算实际抵扣金额
  let totalDiscount
  if (userHasTotalTicket.value >= totalSeatScoreMoney) {
    // 情况1：优惠券足够，全额抵扣
    totalDiscount = totalSeatScoreMoney
  } else {
    // 情况2：优惠券不足，只能抵扣 userHasTotalTicket
    totalDiscount = userHasTotalTicket.value
  }
  totalDiscount = parseFloat(totalDiscount.toFixed(2))
  // 4. 计算总价（userMoney 总和 + userScoreMoney 总和）
  const baseTotalPrice = parseFloat(
    (totalMinMoney + totalSeatScoreMoney).toFixed(2)
  )
  let acturePayTotalPrice
  // 如果优惠券不足，不足部分需加到总价中
  if (userHasTotalTicket.value >= totalSeatScoreMoney) {
    // 优惠券足够：总价 = userMoney 总和
    acturePayTotalPrice = totalMinMoney
  } else {
    // 优惠券不足：总价 = userMoney 总和 + (userScoreMoney 总和 - 实际抵扣的优惠券金额)
    acturePayTotalPrice = totalMinMoney + (totalSeatScoreMoney - totalDiscount)
  }
  acturePayTotalPrice = parseFloat(acturePayTotalPrice.toFixed(2))
  return {
    baseTotalPrice, // 基础总价（userMoney + userScoreMoney，仅用于显示）
    acturePayTotalPrice, // 实际需支付的总价（含补差）
    totalDiscount // 实际抵扣的优惠券金额
  }
})
// 获取价格图例展示信息
const getAllAreaPrices = computed(() => {
  const areas: Array<{
    areaId: string
    name: string
    color: string
    price: number
  }> = []

  // 当支持分区定价时）
  if (hasAreaPricing.value) {
    const defaultArea = sessionInfo.value.areaPrice?.find((a) => a.area === '0')
    if (defaultArea) {
      // 查找该区域的第一个座位获取价格
      const sampleSeat = seatList.value.find((seat) => seat.areaId === '0')
      areas.push({
        areaId: '0',
        name: '普通区',
        color: '#73d0f5',
        price: sampleSeat?.zsjg || defaultArea.showPrice // 优先使用座位价格
      })
    }
    // 添加其他分区
    sessionInfo.value.areaPrice?.forEach((ele) => {
      if (ele.area !== '0') {
        // 查找该区域的第一个座位获取价格
        const sampleSeat = seatList.value.find(
          (seat) => seat.areaId === ele.area
        )
        areas.push({
          areaId: ele.area,
          name: ele.area || `${ele.area}区`,
          color: getAreaColor(ele.area),
          price: sampleSeat?.zsjg || ele.showPrice // 优先使用座位价格
        })
      }
    })
  }

  return areas
})

// 2分钟刷新座位数据
const startSeatRefresh = () => {
  // console.log('reloadTimer', reloadTimer)
  if (reloadTimer) {
    clearTimeout(reloadTimer)
    reloadTimer = null
  }
  if (!isPageActive) return // 如果页面不活跃，停止递归
  console.log('进行循环')
  getAllSeat(sessionInfo.value) // 获取最新座位
  // 2分钟后再次调用（递归）
  reloadTimer = setTimeout(() => {
    startSeatRefresh()
  }, 2 * 60 * 1000) as unknown as number
}
// 计算剩余时间（秒）
const calculateRemainingTime = () => {
  if (!sessionInfo.value.stopSellTime) return 0
  const now = new Date()
  const stopTime = new Date(sessionInfo.value.stopSellTime.replace(' ', 'T'))
  return Math.max(0, Math.floor((stopTime.getTime() - now.getTime()) / 1000))
}
// 初始化倒计时
const initCountdown = () => {
  remainTime.value = calculateRemainingTime()
  // 清除旧定时器
  // if (timer) clearInterval(timer)
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  // 设置新定时器（每秒更新）
  timer = setInterval(() => {
    remainTime.value = calculateRemainingTime()
    // 检查是否过期
    if (remainTime.value <= 0) {
      isStopSell.value = true
      clearInterval(timer!)
      uni.showModal({
        title: '温馨提示',
        content: `场次${sessionInfo.value.showTime}已停止售票,将重新获取场次`,
        showCancel: false,
        success: () => {
          uni.redirectTo({
            url: '/packageF/pages/selectSession/index'
          })
        }
      })
    }
    // 检查30分钟警告
    else if (remainTime.value <= 1800 && !showWarning.value) {
      showWarning.value = true
      uni.showToast({
        title: '当前场次将在30分钟内停止售票，请注意选座时间',
        icon: 'none',
        duration: 3000
      })
    }
  }, 1000) as unknown as number
}
// 获取用户总的现金抵用券
const getMemberTotalChangLaiQuan = async () => {
  const { data } = await moneyApi.getMemberSomeWalletMoney({
    walletRule: enumAll.wallet_rule_id_enum.现金抵用券
  })
  useToatlChanglaiQuan.value = Math.floor(data * 10) / 10
  // console.log(data, '用户拥有的总的现金抵用券')
}
// 获取用户总的复来券
const getMemberTotalFulaiquan = async () => {
  const { data } = await moneyApi.getMemberTotalFulaiquan()
  // console.log(data, '复来券')
  useTotalFulaiquan.value = data
}
// 获取用户总的花积分
const getMemberTotalHuajifen = async () => {
  const { data } = await moneyApi.getMemberSomeWalletMoney({
    walletRule: enumAll.wallet_rule_id_enum.花积分钱包
  })
  // console.log(data, '花积分')
  useTotalHuajifen.value = data
}
// 获取所有座位
const getAllSeat = async (obj: any) => {
  uni.showLoading({ title: '加载中，请稍后', mask: true })
  try {
    const { data } = await movieApi
      .getAllSeatApi({
        showId: obj.showId,
        addFlag: obj.areaPrice.length > 0 ? 1 : 0,
        type: shopMode.value
      })
      .finally(() => {
        uni.hideLoading()
      })
    // console.log('座位', data)
    maxNum.value = data.restrictions
    seatList.value = data.seats.map((ele: any) => {
      return {
        ...ele,
        //每张票的价格
        zsjg: (ele.userMoney + ele.userScoreMoney).toFixed(2)
      }
    })
    // uni.setStorageSync('allSeat', JSON.stringify(seatList.value))
  } catch (e) {
    console.log('获取座位error', e)
  }
}
// 获取指定座位,传入的是行号列号
const getSeat = (rowNo: any, columnNo: any) => {
  const row = showSeatList.value.find((r: any) => r.rowNo === rowNo)
  return row?.seats[columnNo] || null
}
// 检查是否选中
const isSeatSelected = (rowNo: any, columnNo: any) => {
  const seat = getSeat(rowNo, columnNo)
  return selectedSeatList.value.some((s) => s.seatId === seat?.seatId)
}
// 获取座位状态类
const getSeatStatus = (rowNo: any, columnNo: any) => {
  const classes: string[] = []
  // 获取到座位
  const seat = getSeat(rowNo, columnNo)
  // 当前行和列是否有座位
  if (!seat) return 'empty'
  // 座位状态类
  classes.push(seat.status === 'N' ? 'available' : 'unavailable')
  // 情侣座类
  if (seat.loveStatus === 1) {
    classes.push('loveseat')
  }
  // 添加分区样式
  if (seat.areaId !== null) {
    classes.push('area-seat')
  }
  return classes.join(' ')
}
// 定义颜色生成函数
const getAreaColor = (areaId: string) => {
  // 扩展颜色数组到16或32种
  const colors = [
    '#33FF57',
    '#6c1806',
    '#FF33E0',
    '#e1ef06',
    '#A633FF',
    '#FF3333',
    '#33FFDD',
    '#340ca5',
    '#FFA533',
    '#085491',
    '#8C33FF',
    '#FF33A5',
    '#33FFA5',
    '#FF5733',
    '#33FF8C',
    '#8CFF33'
  ]
  // 更好的哈希函数
  let hash = 0
  for (let i = 0; i < areaId.length; i++) {
    const char = areaId.charCodeAt(i)
    hash = (hash << 5) - hash + char // 类似djb2哈希算法
    hash = hash & hash // 转换为32位整数
  }
  return colors[Math.abs(hash) % colors.length]
}
// 获取座位的动态样式
const getSeatStyle = (rowNo: any, columnNo: any) => {
  const seat = getSeat(rowNo, columnNo)
  if (!seat || seat.areaId === null) return {}
  const area = getAllAreaPrices.value.find((a) => a.areaId === seat.areaId)
  if (!area) return {}
  return {
    borderColor: area.color
  }
}
// 点击座位
const handleClickSeat = (rowNo: any, columnNo: any) => {
  const seat = getSeat(rowNo, columnNo)
  if (!seat || seat.status !== 'N') return
  // 处理情侣座
  if (seat.loveStatus === 1 || seat.loveStatus === 2) {
    // 找到情侣座对应的另一个座位, 左座 → 找右座 右座 → 找左座
    const partnerColumnNo =
      seat.loveStatus === 1 ? parseInt(columnNo) + 1 : parseInt(columnNo) - 1
    const partnerSeat = getSeat(rowNo, partnerColumnNo.toString())
    // 检查是否已经选中
    const isSelected = isSeatSelected(rowNo, columnNo)
    if (!isSelected) {
      // 检查是否超过最大选择数量
      if (selectedSeatList.value.length + 2 > maxNum.value) {
        uni.showToast({
          title: `最多只能选择${maxNum.value}个座位`,
          icon: 'none'
        })
        return
      }
      // 添加当前座位和情侣座
      selectedSeatList.value.push(seat)
      if (partnerSeat && partnerSeat.status === 'N') {
        selectedSeatList.value.push(partnerSeat)
      }
    } else {
      // 移除当前座位和情侣座
      selectedSeatList.value = selectedSeatList.value.filter(
        (s) =>
          s.seatId !== seat.seatId &&
          (partnerSeat ? s.seatId !== partnerSeat.seatId : true)
      )
    }
  }
  // 处理普通座位
  else {
    const index = selectedSeatList.value.findIndex(
      (s) => s.seatId === seat.seatId
    )
    if (index === -1) {
      if (selectedSeatList.value.length >= maxNum.value) {
        uni.showToast({
          title: `最多只能选择${maxNum.value}个座位`,
          icon: 'none'
        })
        return
      }
      selectedSeatList.value.push(seat)
    } else {
      selectedSeatList.value.splice(index, 1)
    }
  }
}
// 点击x取消选座
const handleCancleSeat = (index: number) => {
  const seat = selectedSeatList.value[index]
  // 如果是情侣座（左座或右座），找到并移除对应的情侣座
  if (seat.loveStatus === 1 || seat.loveStatus === 2) {
    // 找到情侣座的另一个座位（左座找右座，右座找左座）
    const partnerColumnNo =
      seat.loveStatus === 1
        ? parseInt(seat.columnNo) + 1 // 左座 → 右座
        : parseInt(seat.columnNo) - 1 // 右座 → 左座
    // 在已选座位中查找对应的情侣座
    const partnerSeatIndex = selectedSeatList.value.findIndex(
      (s) => s.rowNo === seat.rowNo && s.columnNo === partnerColumnNo.toString()
    )
    // 移除当前座位和对应的情侣座（如果存在）
    selectedSeatList.value.splice(index, 1)
    if (partnerSeatIndex !== -1) {
      // 由于数组已经变化，需要调整索引（如果 partnerSeatIndex > index）
      const adjustedIndex =
        partnerSeatIndex > index ? partnerSeatIndex - 1 : partnerSeatIndex
      selectedSeatList.value.splice(adjustedIndex, 1)
    }
  }
  // 普通座位，直接移除
  else {
    selectedSeatList.value.splice(index, 1)
  }
}
// 点击购票
const hanleClickSelectSeatBtn = () => {
  // if (remainTime.value <= 300) {
  //   uni.showModal({
  //     title: '温馨提示',
  //     content: `距离停止售卖不足5分钟，已无法发起支付，请选择其他场次`,
  //     showCancel: false,
  //     success: () => {
  //       uni.redirectTo({
  //         url: '/packageF/pages/selectSession/index'
  //       })
  //     }
  //   })
  //   return
  // }
  if (isStopSell.value) {
    uni.showToast({
      title: `场次${sessionInfo.value.showTime}已停止售票,将重新获取场次`,
      icon: 'none'
    })
    return
  }
  // console.log('购票', selectedSeatList.value)
  const tempArr = selectedSeatList.value.map((ele) => {
    return {
      seatId: ele.seatId,
      seatName: ele.seatNo
    }
  })
  // console.log('场次', sessionInfo.value)
  // console.log('tempArr', tempArr)
  // console.log('计算的价格', calculatePrice)
  const tempObj = {
    yymc: uni.getStorageSync('xzCinemaName'),
    dymc: movieInfo.value.movieName,
    dytp: movieInfo.value.posterUrl,
    kcsj: sessionInfo.value.showTime,
    ytmc: sessionInfo.value.hallName,
    ccid: sessionInfo.value.showId,
    cclx: sessionInfo.value.showVersionType,
    xzzw: tempArr,
    isfq: hasAreaPricing.value == true ? 1 : 0,
    zwwz: tempArr
      .map((ele) => {
        return ele.seatName
      })
      .join(' '),
    // 总的最多可抵扣
    toatlMaxDk: selectedSeatList.value.reduce((sum, item) => {
      return sum + (item.highestScoreMoney || 0) // 确保处理可能不存在的属性
    }, 0)
  }
  uni.navigateTo({
    url: `/packageF/pages/moviePayment/index`
  })
  uni.setStorageSync('orderNeed', JSON.stringify(tempObj))
}
</script>

<style lang="scss" scoped>
.seat-container {
  /* 影院屏幕区域 */
  .screen-area {
    padding: 20rpx;
    text-align: center;
    //    图例样式
    .legend {
      display: flex;
      justify-content: center;
      gap: 15rpx;
      margin-top: 20rpx;
      padding: 10rpx;
      border-radius: 8rpx;
      flex-wrap: wrap;
      .legend-item {
        display: flex;
        align-items: center;
        font-size: 20rpx;
        color: #666;

        .legend-color {
          width: 40rpx;
          height: 36rpx;
          border-radius: 8rpx;
          margin-right: 5rpx;

          &.available {
            background-color: #fff;
          }

          &.selected {
            background-color: #04cdbb;
          }

          &.sold {
            background-color: black;
            // border: 1rpx dashed #d9d9d9;
          }

          &.lover {
            background-color: #fff;
            font-size: 24rpx;
            background-image: url(../../static/ax.png);
            background-size: contain;
            background-position: center center;
            background-repeat: no-repeat;
          }
          &.disabled {
            background-color: red;
            border: 1rpx solid #e8e8e8;
          }
        }
      }
    }
    .screen-label {
      font-size: 20rpx;
      color: #999;
      margin: 20rpx 0;
    }
    .screen-arch {
      width: 405rpx;
      margin: 20rpx auto;
    }
  }
  // 座位区域
  .seating-area {
    display: flex;
    width: 750rpx;
    height: 505rpx;
    padding: 0 10rpx;
    transition: transform 0.3s ease;
    // 放大状态下的样式
    &.zoomed {
      width: auto !important;
      max-width: 100vw;
      padding: 0 20rpx;
      overflow-x: auto; // 放大时允许横向滚动
      .seat-row {
        min-width: max-content;
      }
      .seatKuai {
        width: 30rpx !important;
        height: 36rpx !important;
        margin-right: 10rpx !important;
        transition: all 0.3s ease;
      }
    }
    .row-labels {
      // margin-right: 5rpx;
      border-radius: 20rpx;
      color: #bbb;
      .row-label {
        transition: all 0.3s ease;
        line-height: 36rpx;
        font-size: 24rpx;
        text-align: center;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        transition: all 0.3s ease; /* 添加平滑过渡 */
      }
    }

    .seats-container {
      flex: 1;
      min-width: 0;
    }
    .seat-row {
      display: flex;
      gap: 2rpx;
      padding: 0 10rpx;
    }

    .seatKuai {
      transition: all 0.3s ease;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      width: v-bind('seatSize + "rpx"');
      height: v-bind('seatSize * 1.2 + "rpx"');
      margin-right: v-bind('seatSpacing + "rpx"');
      flex-shrink: 0;
      // 确保极端情况下仍可点击
      min-width: 10rpx;
      min-height: 10rpx;
      position: relative;

      // 可用座位基础样式
      &.available {
        background-color: #fff;
        color: #ccc;
        &:active {
          transform: scale(0.95);
        }
      }

      // 不可用座位
      &.unavailable {
        background-color: red !important;
        color: red;
        border-color: #d9d9d9 !important;
      }

      // 选中状态
      &.selected {
        background-color: #04cdbb !important;
        color: #fff !important;
        border-color: transparent !important;
      }
      // 情侣座图标
      /* 情侣左座 */
      &.couple-left {
        border-radius: 8rpx 0 0 8rpx;
        margin-right: -1rpx;
        width: calc(
          v-bind('seatSize + "rpx"') + 3rpx
        ) !important; // 增加负边距的绝对值
        background-image: url(../../static/ax.png);
        background-size: contain;
        background-position: center center;
        background-repeat: no-repeat;
      }

      /* 情侣右座 */
      &.couple-right {
        border-radius: 0 8rpx 8rpx 0;
        margin-left: -1rpx;
        width: calc(
          v-bind('seatSize + "rpx"') + 4rpx
        ) !important; // 增加负边距的绝对值
        background-image: url(../../static/ax.png);
        background-size: contain;
        background-position: center center;
        background-repeat: no-repeat;
      }
      // 分区座位样式
      &.area-seat {
        border-width: 2rpx;
        border-style: solid;
        background-color: transparent;
      }

      // 不显示的空座位
      &.empty {
        visibility: hidden;
        pointer-events: none;
      }
    }
  }
  // 价格图例
  .legend-container {
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    margin: 20rpx 0;

    .legend-item {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      margin-right: 5rpx;

      .legend-color {
        width: 20rpx;
        height: 20rpx;
        border-radius: 3rpx;

        border: 2rpx solid;
        background-color: transparent;
      }
    }
  }

  .footer {
    .btn-area {
      // 选择按钮样式
      .select-btn {
        width: 726rpx;
        height: 80rpx;
        background: rgba(255, 108, 24);
        border-radius: 42rpx;
        font-size: 28rpx;
        line-height: 84rpx;
        color: white;
      }
      .disabled-btn {
        width: 726rpx;
        height: 80rpx;
        background: rgba(255, 108, 24, 0.5);
        border-radius: 42rpx;
        color: #999;
        font-size: 28rpx;
        line-height: 84rpx;
        color: white;
      }
    }
    .movie-area {
      width: 726rpx;
      min-height: 124rpx;
      background: white;
      border-radius: 8rpx;
      margin: 0 auto;
      margin-bottom: 20rpx;
      padding: 20rpx;
      .bt {
        color: #333;
        margin-bottom: 10rpx;
        display: flex;
        align-items: center;
      }
      .yxzw {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        padding: 0 20rpx;

        padding-left: 50rpx;
        .yxzw-item {
          width: 182rpx;
          height: 94rpx;
          background: #eee;
          border-radius: 12rpx;
          margin-right: 20rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 10rpx;
          margin-bottom: 20rpx;
          .yxzw-l {
            text-align: center;
          }
          .yxzw-r {
            margin-right: 10rpx;
          }
          .jq {
            color: #d70208;
            font-weight: bold;
            display: flex;
            > view {
              display: flex;
            }
          }
        }
      }
    }
    .jgbox {
      text-align: center;
      border-radius: 5rpx;
      height: 100rpx;
      font-size: 32rpx;
      .txbox {
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .redwz {
        color: #d70208;
        margin-right: 10rpx;
      }
      .hxwz {
        color: #999;
        text-decoration: line-through;
        font-size: 22rpx;
      }
    }
  }
}
.overwz {
  //   单行文本省略号
  width: 100%;
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
}
</style>
